<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤管理 - OA办公系统</title>
    <link href="${pageContext.request.contextPath}/css/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/fontawesome.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<script src="${pageContext.request.contextPath}/js/jquery-3.6.0.js"></script>
<body class="bg-gray-50 h-screen overflow-auto p-6">
    <div class="container mx-auto fade-in">
        <!-- 页面标题 -->
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-800">考勤管理</h1>
            <div class="flex space-x-2">
                <button class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center btn-hover-effect" onclick="clockIn()">
                    <i class="fas fa-clock mr-2"></i>
                    <span>打卡签到</span>
                </button>
                <button class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 flex items-center btn-hover-effect">
                    <i class="fas fa-file-export mr-2"></i>
                    <span>导出报表</span>
                </button>
                <div class="relative">
                    <input type="text" placeholder="搜索考勤记录" class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <i class="fas fa-search absolute right-3 top-3 text-gray-400"></i>
                </div>
            </div>
        </div>

        <!-- 考勤概览 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6" id="attendanceOverview">
            <!-- 出勤卡片 -->
            <div class="bg-white rounded-lg shadow p-5 card-hover">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-gray-500 text-sm">本月出勤</p>
                        <h2 id="attendanceDays" class="text-3xl font-bold text-gray-800">--天</h2>
                    </div>
                    <div class="h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-calendar-check text-blue-500 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="attendanceRateBar" class="bg-blue-500 h-2 rounded-full" style="width: 0%"></div>
                    </div>
                    <p id="attendanceRateText" class="text-xs text-gray-500 mt-1">出勤率 --%</p>
                </div>
            </div>

            <!-- 迟到卡片 -->
            <div class="bg-white rounded-lg shadow p-5 card-hover">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-gray-500 text-sm">迟到</p>
                        <h2 id="lateCount" class="text-3xl font-bold text-gray-800">--次</h2>
                    </div>
                    <div class="h-12 w-12 bg-yellow-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-hourglass-half text-yellow-500 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <div class="flex justify-between text-xs text-gray-500">
                        <span id="lastLateDate">最近一次: --</span>
                        <span id="lastLateMinutes" class="text-yellow-500">--</span>
                    </div>
                </div>
            </div>

            <!-- 请假卡片 -->
            <div class="bg-white rounded-lg shadow p-5 card-hover">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-gray-500 text-sm">请假</p>
                        <h2 id="leaveDays" class="text-3xl font-bold text-gray-800">--天</h2>
                    </div>
                    <div class="h-12 w-12 bg-purple-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-user-clock text-purple-500 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <div class="flex justify-between text-xs text-gray-500">
                        <span>年假剩余</span>
                        <span id="annualLeaveLeft" class="text-purple-500">--天</span>
                    </div>
                </div>
            </div>

            <!-- 加班卡片 -->
            <div class="bg-white rounded-lg shadow p-5 card-hover">
                <div class="flex justify-between items-center">
                    <div>
                        <p class="text-gray-500 text-sm">加班</p>
                        <h2 id="overtimeHours" class="text-3xl font-bold text-gray-800">--小时</h2>
                    </div>
                    <div class="h-12 w-12 bg-red-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-business-time text-red-500 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <div class="flex justify-between text-xs text-gray-500">
                        <span>本月加班费</span>
                        <span id="overtimePay" class="text-red-500">¥--</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 考勤分类标签 -->
        <div class="bg-white rounded-lg shadow mb-6">
            <div class="flex border-b overflow-x-auto">
                <button class="px-6 py-3 text-blue-500 border-b-2 border-blue-500 font-medium">我的考勤</button>
                <button class="px-6 py-3 text-gray-500 hover:text-blue-500">部门考勤</button>
                <button class="px-6 py-3 text-gray-500 hover:text-blue-500">请假申请</button>
                <button class="px-6 py-3 text-gray-500 hover:text-blue-500">加班申请</button>
                <button class="px-6 py-3 text-gray-500 hover:text-blue-500">外出申请</button>
                <button class="px-6 py-3 text-gray-500 hover:text-blue-500">考勤统计</button>
            </div>
        </div>

        <!-- 日期筛选 -->
        <div class="bg-white rounded-lg shadow p-4 mb-6">
            <div class="flex flex-wrap items-center justify-between">
                <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                        <span class="text-gray-500 mr-2">日期范围:</span>
                        <input type="date" value="2023-06-01" class="border border-gray-300 rounded px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <span class="mx-2">至</span>
                        <input type="date" value="2023-06-30" class="border border-gray-300 rounded px-3 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                <div class="flex items-center space-x-2">
                    <button class="px-4 py-1 bg-blue-100 text-blue-600 rounded hover:bg-blue-200">
                        <i class="fas fa-filter mr-1"></i>
                        筛选
                    </button>
                    <button class="px-4 py-1 text-gray-500 hover:text-blue-500">
                        <i class="fas fa-redo-alt mr-1"></i>
                        重置
                    </button>
                </div>
            </div>
        </div>

        <!-- 考勤记录表格 -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <table class="w-full enhanced-table">
                <thead>
                    <tr class="bg-gray-50 text-left">
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">星期</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">上班时间</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">下班时间</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">工时</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">备注</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">

                </tbody>
            </table>

        </div>
    </div>
</body>
<script>
    //打卡功能
    function clockIn() {
        $.ajax({
            url: "${pageContext.request.contextPath}/attendance",
            type: "post",
            data: {
                method: "clockIn",
                employeeId: getCurrentUserId()
            },
            dataType: "json",
            success: function(response) {
                if(response.alreadyClockIn) {
                    // 显示"已打卡"提示，可能禁用打卡按钮
                    alert("您今日已打卡，无需重复操作");
                } else if(response.code === "200") {
                    // 显示"打卡成功"
                    alert("打卡成功！");
                    loadAttendanceData()
                } else {
                    // 处理错误情况
                    alert("打卡失败：" + response.msg);
                }
            },
            error: function(xhr, status, error) {
                alert("请求失败: " + error);
            }
        });
    }

    // 导出报表功能
    function exportReport() {
        if(!currentUserId) {
            alert("请先登录");
            return;
        }

        // 这里可以添加导出逻辑
        showSuccessToast("报表导出请求已发送，请稍后查看下载");
    }

    // 加载考勤数据
    function loadAttendanceData() {
        $.ajax({
            url: "${pageContext.request.contextPath}/attendance",
            type: "post",
            data: {
                method: "getAttendanceRecords",
                employeeId: getCurrentUserId()
            },
            dataType: "json",
            success: function(response) {
                if(response.code === "200") {
                    // 清空表格
                    $("table tbody").empty();

                    if (!response.data || response.data.length === 0) {
                        $("table tbody").append('<tr><td colspan="7" class="text-center py-4">暂无考勤记录</td></tr>');
                        return;
                    }

                    // 填充数据
                    $.each(response.data, function(index, item) {
                        // 根据状态设置不同的样式
                        var date = new Date(item.date);
                        var formattedDate = formatDate(date);
                        var weekDay = ["日", "一", "二", "三", "四", "五", "六"][date.getDay()];

                        // 计算工时
                        var workingHours = "-";
                        if(item.check_in_time && item.check_out_time) {
                            var checkIn = new Date(item.check_in_time);
                            var checkOut = new Date(item.check_out_time);
                            var hours = (checkOut - checkIn) / (1000 * 60 * 60);
                            workingHours = hours.toFixed(1) + "小时";
                        }

                        // 状态样式
                        var statusClass = "";
                        var statusText = item.status || "正常";

                        switch(statusText) {
                            case "正常":
                                statusClass = "bg-green-100 text-green-800";
                                break;
                            case "迟到":
                                statusClass = "bg-yellow-100 text-yellow-800";
                                break;
                            case "早退":
                                statusClass = "bg-orange-100 text-orange-800";
                                break;
                            default:
                                statusClass = "bg-gray-100 text-gray-800";
                        }

                        var row = '<tr class="hover:bg-blue-50">' +
                            '<td class="px-6 py-4 whitespace-nowrap">' + formattedDate + '</td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">星期' + weekDay + '</td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">' + (item.check_in_time ? formatTime(item.check_in_time) : '-') + '</td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">' + (item.check_out_time ? formatTime(item.check_out_time) : '-') + '</td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">' + workingHours + '</td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">' +
                            '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ' +
                            statusClass + '">' + statusText + '</span></td>' +
                            '<td class="px-6 py-4 whitespace-nowrap">' + (item.remark || '-') + '</td>' +
                            '</tr>';

                        $("table tbody").append(row);
                    });
                } else {
                    alert("获取考勤数据失败: " + (response.msg || "未知错误"));
                }
            },
            error: function(xhr, status, error) {
                alert("请求考勤数据失败: " + error);
            }
        });
    }

    function loadAttendanceOverview() {
        const employeeId = getCurrentUserId();
        if (!employeeId) return;

        $.ajax({
            url: "${pageContext.request.contextPath}/attendance",
            type: "post",
            data: {
                method: "getAttendanceOverview",
                employeeId: employeeId
            },
            dataType: "json",
            success: function(response) {
                if(response.code === "200") {
                    updateOverviewCards(response.data);
                } else {
                    showErrorToast(response.msg || "获取考勤概览失败");
                }
            },
            error: function(xhr, status, error) {
                showErrorToast("请求考勤概览失败: " + error);
            }
        });
    }

    function updateOverviewCards(data) {
        // 更新出勤数据
        $('#attendanceDays').text(data.attendanceDays + '天');
        $('#attendanceRateBar').css('width', data.attendanceRate + '%');
        $('#attendanceRateText').text('出勤率 ' + data.attendanceRate + '%');

        // 更新迟到数据
        $('#lateCount').text(data.lateCount + '次');
        if(data.lastLateDate) {
            $('#lastLateDate').text('最近一次: ' + data.lastLateDate);
            $('#lastLateMinutes').text('迟到' + data.lastLateMinutes + '分钟');
        } else {
            $('#lastLateDate').text('最近一次: -');
            $('#lastLateMinutes').text('无迟到记录');
        }

        // 更新请假数据
        $('#leaveDays').text(data.leaveDays + '天');
        $('#annualLeaveLeft').text(data.annualLeaveLeft + '天');

        // 更新加班数据
        $('#overtimeHours').text(data.overtimeHours + '小时');
        $('#overtimePay').text('¥' + data.overtimePay);
    }

    function formatDate(dateInput) {
        if (!dateInput) return "";

        const date = new Date(typeof dateInput === 'number' ? dateInput : dateInput);

        return date.getFullYear() + "/" +
            (date.getMonth() + 1).toString().padStart(2, '0') + "/" +
            date.getDate().toString().padStart(2, '0');
    }


    // 格式化时间显示
    function formatTime(datetime) {
        if (!datetime) return "-";
        // 如果datetime已经是Date对象，直接使用
        const date = datetime instanceof Date ? datetime : new Date(datetime);

        // 检查是否是有效日期
        if (isNaN(date.getTime())) return "-";

        return date.getHours().toString().padStart(2, '0') + ":" +
            date.getMinutes().toString().padStart(2, '0');
    }

    function getCurrentUserId() {
        return sessionStorage.getItem('userId');
    }

    // 页面加载时获取考勤数据
    $(document).ready(function() {
        loadAttendanceData();
        loadAttendanceOverview();
    });
</script>
</html>
